package com.thingsgrid.mqtthelper.service.impl;

import com.thingsgrid.mqtthelper.config.MqttAdapterConfig;
import com.thingsgrid.mqtthelper.config.MqttGateway;
import com.thingsgrid.mqtthelper.service.MqttHelperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 功能说明：mqtt连接方式
 *
 * @author 李龙飞
 * @since 2019/8/27 9:51
 */

@Service
@Slf4j
public class MqttHelperServiceImpl implements MqttHelperService {

	@Autowired
	private MqttGateway mqttGateway;

	private static MqttPahoMessageDrivenChannelAdapter adapter;

	public MqttHelperServiceImpl(){
		adapter = MqttAdapterConfig.getInstanceAdapter();
	}

	/**
	 *说明
	 *@author lilongfei
	 *@since 2019/8/27 9:59
	 */
	@Override
	public boolean addMqttTopic(String[] topicArr) {
		adapter = MqttAdapterConfig.getInstanceAdapter();
		if(topicArr.length==0){
			return false;
		}
		for(String topic:topicArr){
			adapter.addTopic(topic,1);
		}
		return true;
	}

	/**
	 *说明：删除topic
	 *@author lilongfei
	 *@since 2019/8/27 9:59
	 */
	@Override
	public boolean removeMqttTopic(String topic) {
		adapter = MqttAdapterConfig.getInstanceAdapter();
		if(StringUtils.isEmpty(topic)){
			return false;
		}
		adapter.removeTopic(topic);
		return true;
	}

	/**
	 *说明：发送消息
	 *@author lilongfei
	 *@since 2019/8/27 9:59
	 */
	@Override
	public Object sendMsg(String topic, String jsonData) {
		mqttGateway.sendToMqtt(jsonData,topic);
		return "发送成功";
	}

}
